package com.jf.filedownload;

import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * Created with IntelliJ IDEA
 * Description:
 * User:22954
 * Date:2024-09-21
 * Time:17:40
 */
@WebServlet(name = "FileDownloadServlet", urlPatterns = "/fileDownloadServlet")
public class FileDownloadServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        // 1.获得请求下载文件名
        String downloadFileName = req.getParameter("name");
        // 2.根据文件后缀, 获得浏览器解析服MIME, 并设置为返回标头
        String mimeType = req.getServletContext().getMimeType(downloadFileName);
        resp.setContentType(mimeType);
        // 3.设置响应头  设置Content-Disposition
        //      attachment----指示浏览器以下载方式处理响应    filename="..."----设置下载时的文件名
        //      URLEncoder.encode(String s, String enc)----将文件名按URL编码,并指定编码格式为enc(一般为utf-8)
        //          浏览器的编码类型默认为URL编码,不指定编码类型,中文文件名会无法识别,Tomcat会默认将文件名设定为当前Servlet的name
        resp.setHeader("Content-Disposition", "attachment; filename=\"" +
                URLEncoder.encode(downloadFileName,"utf-8") + "\"");
        // 4.获得文件路径
        String downloadFilePath = "/download/" + downloadFileName;
        // 5.这里将下载文件放置在resources目录下,Tomcat启动后路径在类的跟目录下,直接获得输入流
        InputStream inputStream = FileDownloadServlet.class.getResourceAsStream(downloadFilePath);
        OutputStream outputStream = resp.getOutputStream();
        if (inputStream != null) {
            // 6.运用IO工具,将输入流对拷至输出流  输入流为文件,输出流为客户端(浏览器)
            IOUtils.copy(inputStream, outputStream);
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
}
